﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using System.Windows.Controls;

namespace ReadLineParser;

using Core;

public partial class MainWindow
{
    private String _currentFilePath = String.Empty;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void New_Click(Object sender, RoutedEventArgs e)
    {
        EditorTextBox.Clear();
        _currentFilePath = String.Empty;
    }

    private void Open_Click(Object sender, RoutedEventArgs e)
    {
        var openFileDialog = new OpenFileDialog();

        if (openFileDialog.ShowDialog() == true)
        {
            _currentFilePath = openFileDialog.FileName;
            EditorTextBox.Text = File.ReadAllText(_currentFilePath);
        }
    }

    private void Save_Click(Object sender, RoutedEventArgs e)
    {
        if (String.IsNullOrEmpty(_currentFilePath))
        {
            SaveAs();
        }
        else
        {
            File.WriteAllText(_currentFilePath, EditorTextBox.Text);
        }
    }

    private void SaveAs_Click(Object sender, RoutedEventArgs e)
    {
        SaveAs();
    }

    private void SaveAs()
    {
        var saveFileDialog = new SaveFileDialog();

        if (saveFileDialog.ShowDialog() == true)
        {
            _currentFilePath = saveFileDialog.FileName;
            File.WriteAllText(_currentFilePath, EditorTextBox.Text);
        }
    }

    private void Copy_Click(Object sender, RoutedEventArgs e)
    {
        EditorTextBox.Copy();
    }

    private void Paste_Click(Object sender, RoutedEventArgs e)
    {
        EditorTextBox.Paste();
    }

    private void Cut_Click(Object sender, RoutedEventArgs e)
    {
        EditorTextBox.Cut();
    }

    private void Undo_Click(Object sender, RoutedEventArgs e)
    {
        EditorTextBox.Undo();
    }

    private void Analyze_Click(Object sender, RoutedEventArgs e)
    {
        var input = EditorTextBox.Text;

        AnalyzeInput(input);
    }

    private void AnalyzeInput(String input)
    {
        try
        {
            MessagesTreeView.Items.Clear();

            var tokens = LexicalAnalyzer.Analyze(input);
            if (SyntacticAnalyzer.Analyze(tokens))
            {
                DisplayParseTree(tokens);
                MessagesTreeView.Items.Add("yes");
            }
            else
            {
                MessagesTreeView.Items.Add("no");
            }
        }
        catch (Exception ex)
        {
            MessagesTreeView.Items.Add($"Error: {ex.Message}");
        }
    }

    private void DisplayParseTree(List<String> tokens)
    {
        var tree = new TreeViewItem { Header = "TREE" };
        foreach (var token in tokens)
        {
            tree.Items.Add(new TreeViewItem { Header = token });
        }

        MessagesTreeView.Items.Clear();
        MessagesTreeView.Items.Add(tree);
    }
}